<template>
  <div class="">
    <div class='flex-jc-sb'>
      <div class="section-title">{{ title }}</div>
      <ga-dropdown>
        <ga-space size="medium" @click.stop="() => { }">
          <ga-badge status="success" v-if="isSuccess" />
          <ga-badge status="danger" v-else />
          {{ currentPort }}
          <icon-down />
        </ga-space>
        <template #content>
          <ga-menu @menu-item-click="onClick">
            <ga-menu-item v-for="item in items" :key="item.key">
              <span>{{ item.label }}</span>
            </ga-menu-item>

          </ga-menu>
        </template>
      </ga-dropdown>
    </div>
    <Chart :option="portData" :height="height" class='custom-chart' ref="chartRef" />
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch, } from 'vue';
import Chart from '@/components/Charts'
let customChart = [];
let seriesName = [];
const props = defineProps({
  title: String,
  height: {
    type: String,
    default: '250px'
  },
  params: {
    type: Object,
    default: () => ({})
  },
  option: {
    type: Object,
    default: () => ([])
  }
})
const emits = defineEmits(['on-filter'])

const currentPort = ref()
const portData = ref({})
const chartRef = ref()
const optionMap = new Map()
const items = computed(() => {
  return props.option.map((item) => {
    const { port } = item.extra
    optionMap.set(port, item)
    return {
      key: port,
      label: port
    }
  })
})
const onClick = ({ key }) => {
  currentPort.value = key
  portData.value = optionMap.get(key)
}
const chartMouseMove = () => {
  if (!seriesName.length) {
    seriesName = document.getElementsByClassName('seriesName') || [];
  }
  for (let i = 0; i < seriesName.length; i++) {
    seriesName[i].onclick = seriesNameClick;
  }
}

const seriesNameClick = (e) => {
  const url = e.target.getAttribute('data-value');
  emits('on-filter', url)
}
onMounted(() => {
  window.addEventListener('resize', () => {
    console.log(chartRef?.value, 'chartRef');

    chartRef?.value?.echartInstance.resize()
  })
})

watch(() => props.option, (option) => {
  if (!customChart.length) {
    customChart = document.getElementsByClassName('custom-chart') || [];
  }
  if (customChart && customChart.length) {
    for (let i = 0; i < customChart.length; i++) {
      customChart[i].onmousemove = chartMouseMove;
    }
  }
  option !== null && (() => {
    portData.value = (option[0]);
    currentPort.value = (option[0].extra.port)
  })()
})
const isSuccess = computed(() => {
  return portData.value?.series?.[0].data.every(d => d > 114 ? false : true)
})
</script>

<style scoped lang="scss"></style>
